import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";

Vue.use(VueRouter);

// 储存旧push方法
const oldPushMethod = VueRouter.prototype.push
VueRouter.prototype.push = function (location, onComplate = () => { }, onAbort = () => { }) {
    // 内部push方法不变，添加了处理异常的回调函数
    return oldPushMethod.call(this, location, onComplate, onAbort)
}

const oldReplaceMethod = VueRouter.prototype.push
VueRouter.prototype.push = function (location, onComplate = () => { }, onAbort = () => { }) {
    // 内部push方法不变，添加了处理异常的回调函数
    return oldReplaceMethod.call(this, location, onComplate, onAbort)
}
const router = new VueRouter({
    mode: "history",
    routes
});

const whitePath = [
    "login",
    "home",
    "register",
    "search",
    "detail",
    "addCartSuccess",
    "shopCart",
  ];
router.beforeEach(async (to, from, next) => {
    // token校验
    // console.log("1", 1);
    const token = store.state.user.token
    if (token) {
        // console.log("2", 2);
        // 判断是否为登陆页，是则直接去home页
        if (to.name === "login") {
            // console.log("3", 3);
            next("/home")
        } else {
            // console.log("4", 4);
            // 判断是否有用户信息
            const isUserInfo = !!store.state.user.userInfo.nickName
            // 有的话直接放行
            if (isUserInfo) {
                // console.log("5", 5);
                next()
            } else {
                try {
                    // console.log("6", 6);
                    // 用户信息不存在，获取用户信息
                    await store.dispatch("user/getUserInfo")
                    // 存在直接放行
                    next()
                } catch (e) {
                    // console.log("7", 7);
                    // 获取用户信息失败，直接去登录页
                    store.dispatch("user/getResetUser");
                    next(`/login?redirect=${to.name}`)
                }
            }
        }
        // token不存在
    } else {
        // 判断去的地方是否是白名单，去的地方不需要登陆则直接放行
        if (whitePath.includes(to.name)) {
            // console.log("8", 8);
            next()
        } else {
            // console.log("9", 9);
            // 否则再次登陆
            next(`/login?redirect=${to.name}`)
        }
    }
})

export default router;
